<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>交流帖子管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="搜索：">
        <el-input
          size="small"
          v-model="formInline.kw"
          placeholder="输入标题"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-search"
          @click="onSearch"
          >搜索</el-button
        >
        <el-button
          size="small"
          type="success"
          icon="el-icon-edit"
          @click="handleEdit()"
          >我要发帖</el-button
        >
      </el-form-item>
    </el-form>
    <!--列表 noticeId hotelName location floor price status-->
    <el-table size="small" :data="listData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">
      <el-table-column align="center" prop="createTime" label="发帖时间" width="220">
        <template slot-scope="scope">
          <div>{{scope.row.publishTime|timestampToDayHM}}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="user.realName" label="发帖人">
        <template slot-scope="scope">
          <div v-if="scope.row.userId!=null">会员：{{scope.row.user.realName}}</div>
          <div v-else>商家：{{scope.row.admin.nickName}}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="title" label="标签" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.tags!=null&&scope.row.tags!=''">
            <el-tag size="small" type="warning" v-for="(tag,id) in scope.row.tags.split(';')" :key="id">{{ tag }}</el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="title" label="标题" show-overflow-tooltip>
      </el-table-column>
      <!-- <el-table-column align="center" prop="content" label="详情" show-overflow-tooltip>
      </el-table-column> -->
      <el-table-column align="center" label="操作" width="190">
        <template slot-scope="scope">
          <el-button size="mini" type="success" @click="toDetailPage(scope.row.froumId)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>

    <el-dialog
      :title="title"
      :visible.sync="editFormVisible"
      width="60%"
      :close-on-click-modal=false
      @click="closeDialog"
    >
      <el-form
        label-width="120px"
        :model="editForm"
        :rules="rules"
        ref="editForm"
      >
        <el-form-item label="帖子标题" prop="title">
          <el-input
            size="small"
            v-model="editForm.title"
            auto-complete="off"
            placeholder=""
          ></el-input>
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-input
            size="small"
            v-model="editForm.tags"
            auto-complete="off"
            placeholder="如有多个请以分别隔开，如：健康资讯;手机使用"
          ></el-input>
        </el-form-item>
        <el-form-item label="帖子正文" prop="content" id='quillEditorQiniu'>
          <!-- 基于elementUi的上传组件 el-upload-->
          <el-upload
              class="avatar-uploader"
              :action="uploadImgUrl"
              :accept="'image/*'"
              :show-file-list="false"
              :on-success="uploadEditorSuccess"
              :on-error="uploadEditorError"
              :before-upload="beforeEditorUpload">
          </el-upload>
          <quill-editor  class="editor"  v-model="editForm.content" ref="customQuillEditor" :options="editorOption" >
          </quill-editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          class="title"
          @click="submitForm('editForm')"
          >发布</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { AdminForumList,MerchantSaveForum } from '@/api/api.js'
import Pagination from '../../components/Pagination'

const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
  ['blockquote', 'code-block'],

  [{'header': 1}, {'header': 2}],               // custom button values
  [{'list': 'ordered'}, {'list': 'bullet'}],
  [{'script': 'sub'}, {'script': 'super'}],      // superscript/subscript
  [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
  [{'direction': 'rtl'}],                         // text direction

  [{'size': ['small', false, 'large', 'huge']}],  // custom dropdown
  [{'header': [1, 2, 3, 4, 5, 6, false]}],

  [{'color': []}, {'background': []}],          // dropdown with defaults from theme
  [{'font': []}],
  [{'align': []}],
  ['link', 'image'],
  ['clean']                                         // remove formatting button
];

export default {
  data() {
    return {
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      query: {},
      formInline: {
        page: 1,
        limit: 10,
        kw: '',
      },
      editForm: {
        title: "",
        tags: '',
        content: '',
        status: 1,
      },
      title: "发布帖子",
      // rules表单验证
      rules: {
        title: [{ required: true, message: "请输入", trigger: "blur" }],
        content: [{ required: true, message: "请输入", trigger: "blur" }],
      },
      files: {},
      photos: [],
      photoObj: "",
      listData: [], //列表数据
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      },
      currDetailData: {},
      currDetailPics: [],
      uploadImgUrl:"/api/admin/uploadPic",
      uploadUrlPath:"没有文件上传",
      quillUpdateImg:false,
      editorOption:{
        placeholder:'请输入正文',
        modules: {
          toolbar: {
            container: toolbarOptions,  // 工具栏
            handlers: {
              'image': function (value) {
                if (value) {
                  document.querySelector('#quillEditorQiniu .avatar-uploader input').click()
                } else {
                  this.quill.format('image', false);
                }
              },
            }
          }
        }
      },
    }
  },
  // 注册组件
  components: {
    Pagination
  },
 
  created() {
    this.getdata(this.formInline)
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
     // 获取数据列表
     getdata(parameter) {
      console.log('开始获取列表！', parameter)
      this.loading = true
      AdminForumList(parameter)
        .then(res => {
          this.loading = false
          if (res.success) {
            this.listData = res.data.records
            this.pageparm.currentPage = res.data.currentPage
            this.pageparm.pageSize = res.data.pageSize
            this.pageparm.total = res.data.totalrecord;
          } else {
            this.$message({
              type: 'info',
              message: res.msg
            })
          }
        })
        .catch(err => {
          this.editFormVisible = false
          this.loading = false
          this.$message.error('系统繁忙，请稍后再试！')
        })
    },
    // 分页插件事件
    callFather(parm) {
      this.formInline.page = parm.currentPage
      this.formInline.limit = parm.pageSize
      this.getdata(this.formInline)
    },
    //详情
    toDetailPage(fid) {
      this.$router.push({ path: '/admin/mer/forum/commentmgr?fid='+fid })
    },

    //显示编辑界面
    handleEdit: function (index, row) {
      this.editFormVisible = true;
      this.title = "发布帖子";
      this.editForm.title = ""
      this.editForm.tags = ""
      this.editForm.content = ""
      this.currDetailPics = []
      this.photos=[]
    },
    // 编辑、增加页面保存方法
    submitForm(editData) {
      this.$refs[editData].validate((valid) => {
        if (valid) {
          MerchantSaveForum(this.editForm).then((res) => {
            this.editFormVisible = false;
            this.loading = false;
            if (res.success) {
              this.getdata(this.formInline);
              this.$message({
                type: "success",
                message: "保存成功！",
              });
              this.photos=[]
            } else {
              this.$message({
                type: "info",
                message: res.msg,
              });
            }
          })
          .catch((err) => {
            this.editFormVisible = false;
            this.loading = false;
            this.$message.error("保存失败，请稍后再试！");
          });
        } else {
          return false;
        }
      });
    },

    onSearch(){
      this.getdata(this.formInline)
    },

    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormVisible = false;
    },
    closeDialog2() {
      this.detailVisible = false;
    },
    handlePreview(file) {
      console.log(file);
    },
    handleRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    uploadSectionFile(file) {
      console.log('选定图片！')
      const typeArr = ["image/png", "image/gif", "image/jpeg", "image/jpg"];
      const isJPG = typeArr.indexOf(file.raw.type) !== -1;
      const isLt3M = file.size / 1024 / 1024 < 3;
      if (!isJPG) {
        this.$message.error("只能是图片!");
        this.$refs.upload.clearFiles();
        this.files = null;
        return;
      }
      if (!isLt3M) {
        this.$message.error("上传图片大小不能超过 3MB!");
        this.$refs.upload.clearFiles();
        this.files = null;
        return;
      }
      this.files = file.raw;
      // FormData 对象
      var formData = new FormData();
      // 文件对象
      formData.append("file", this.files);
      let config = {
        headers: {
          "Content-Type": "multipart/form-data",
        },
        methods: "post",
      };
      axios.post("http://localhost:9081/api/admin/uploadPic", formData, config).then((res) => {
        if (res.data.success) {
          //this.photoObj = res.data.data.objectId;
          console.log('图片上传成功！', res.data)
          this.photos.push(res.data.data);
          if(this.editForm.pics!=""){
            this.editForm.pics = this.editForm.pics+","+res.data.data
          }else{
            this.editForm.pics = res.data.data
          }
          console.log(this.editForm.pics)
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    // 上传图片成功
    uploadEditorSuccess(res, file) {
      console.log("上传成功")
      // this.$emit('upload',res, file)
      console.log(res, file);
      //拼接出上传的图片在服务器的完整地址
      let imgUrl=res.data;
      let type=imgUrl.substring(imgUrl.lastIndexOf(".")+1);
      console.log(type);
      // 获取富文本组件实例
      let quill = this.$refs.customQuillEditor.quill;
      // 获取光标所在位置
      let length = quill.getSelection().index;
      // 插入图片 res.info为服务器返回的图片地址
      quill.insertEmbed(length, 'image', imgUrl)
      // 调整光标到最后
      quill.setSelection(length + 1)
      //取消上传动画
      this.quillUpdateImg = false;
    },
    // 上传(文件)图片失败
    uploadEditorError(res, file) {
      console.log(res);
      console.log(file);
      //页面提示
      this.$message.error('上传图片失败')
      //取消上传动画
      this.quillUpdateImg = false;
    },
    //上传图片之前async
    beforeEditorUpload(res, file){
      //显示上传动画
      this.quillUpdateImg = true;
      //  const res1 = await uploadImage()
      // console.log(res1,'=====');
      // this.$emit('before',res, file)
      console.log(res);
      console.log(file);
    },
    //上传组件返回的结果
    uploadResult:function (res){
      this.uploadUrlPath=res;
    },
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.quill-editor {
  height: 250px;
  margin-bottom: 100px;
}
</style>

 
 